package com.mlan.userap.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.google.gson.Gson;
import com.mlan.userap.model.MsgFileInfo;
import com.mlan.userap.model.MsgRequ;
import com.mlan.userap.model.MsgResp;
import com.mlan.userap.untils.LogHelper;

import java.util.ArrayList;
import java.util.List;

public class ChatDao {
    private final ChatDatabaseHelper dbHelper;
    private final Gson gson;

    public ChatDao(Context context) {
        dbHelper = new ChatDatabaseHelper(context);
        gson = new Gson();
    }


//    messageDao = new MessageDao(this);
//
//    // 插入一条消息
//    MsgFileInfo fileInfo = new MsgFileInfo("image.jpg", "http://example.com/image.jpg", 2, 0, "http://example.com/thumb.jpg");
//    MsgData msg = new MsgData("msg_001", "group_123", 1001L, 2, null, fileInfo, System.currentTimeMillis());
//        messageDao.insertMessage(msg);
//
//    // 查询某个组的最近 10 条消息
//    List<MsgData> messages = messageDao.getMessagesByGroupId("group_123", System.currentTimeMillis() + 1, 10);
//        for (MsgData m : messages) {
//        Log.d("Chat", "消息类型: " + m.getMsgType() + ", 时间: " + m.getMsgTicks());
//        if (m.getFileInfo() != null) {
//            Log.d("Chat", "附件: " + m.getFileInfo().getResurl());
//        }
//    }
//
//    // 删除一条消息
//        messageDao.deleteMessage("msg_001");


    // 插入一条消息
    public void insertMessage(MsgResp message) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
//        ContentValues values = new ContentValues();
//        values.put("msg_id", message.getMsgId());
//        values.put("group_id", message.getGroupId());
//        values.put("uid_from", message.getUidFrom());
//        values.put("msg_type", message.getMsgType());
//        values.put("msg_content", message.getMsgContent());
//        values.put("file_info", message.getFileInfo() != null ? gson.toJson(message.getFileInfo()) : null);
//        values.put("msg_ticks", message.getMsgTicks());
//        db.insertWithOnConflict("messages", null, values, SQLiteDatabase.CONFLICT_REPLACE);

        String sql = "INSERT OR IGNORE INTO messages " +
                "(msg_id, group_id, uid_from, msg_type, msg_content, file_info, msg_ticks) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";
        db.execSQL(sql, new Object[]{
                message.getMsgId(),
                message.getGroupId(),
                message.getUidFrom(),
                message.getMsgType(),
                message.getMsgContent(),
                message.getFileInfo() != null ? gson.toJson(message.getFileInfo()) : null,
                message.getMsgTicks()
        });
        db.close();
        LogHelper.i("插入完成："+message.getMsgId());
    }

    public void insertMessage(List<MsgResp> msgList) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction(); // 开始事务
        try {
            String sql = "INSERT OR IGNORE INTO messages " +
                    "(msg_id, group_id, uid_from, msg_type, msg_content, file_info, msg_ticks) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?)";
            SQLiteStatement statement = db.compileStatement(sql);

            for (MsgResp message : msgList) {
                statement.clearBindings();
                statement.bindString(1, message.getMsgId());
                statement.bindString(2, message.getGroupId());
                statement.bindLong(3, message.getUidFrom());
                statement.bindLong(4, message.getMsgType());
                if(message.getMsgContent()==null||message.getMsgContent().isEmpty()){
                    statement.bindNull(5);
                }
                else{
                    statement.bindString(5, message.getMsgContent());
                }

                if (message.getFileInfo() != null) {
                    statement.bindString(6, gson.toJson(message.getFileInfo()));
                } else {
                    statement.bindNull(6);
                }
                statement.bindLong(7, message.getMsgTicks());
                long rowId = statement.executeInsert(); // 执行插入，返回插入的行 ID
            }
            db.setTransactionSuccessful(); // 标记事务成功
        } finally {
            db.endTransaction(); // 结束事务
            db.close();
        }
    }
    // 分页查询某个组的消息
    public List<MsgResp> getMessagesByGroupId(String groupId, long beforeTicks, int limit) {
        List<MsgResp> messages = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String query = "SELECT * FROM messages WHERE group_id = ? AND msg_ticks < ? " +
                "ORDER BY msg_ticks DESC LIMIT ?";
        Cursor cursor = db.rawQuery(query, new String[]{groupId, String.valueOf(beforeTicks), String.valueOf(limit)});

        while (cursor.moveToNext()) {
            String fileInfoJson = cursor.getString(cursor.getColumnIndexOrThrow("file_info"));
            MsgFileInfo fileInfo = fileInfoJson != null ? gson.fromJson(fileInfoJson, MsgFileInfo.class) : null;

            MsgResp msg = new MsgResp(
                    cursor.getString(cursor.getColumnIndexOrThrow("msg_id")),
                    cursor.getString(cursor.getColumnIndexOrThrow("group_id")),
                    cursor.getLong(cursor.getColumnIndexOrThrow("uid_from")),
                    cursor.getInt(cursor.getColumnIndexOrThrow("msg_type")),
                    cursor.getString(cursor.getColumnIndexOrThrow("msg_content")),
                    fileInfo,
                    cursor.getLong(cursor.getColumnIndexOrThrow("msg_ticks"))
            );
            messages.add(msg);
        }
        cursor.close();
        db.close();
        return messages;
    }





    // 获取某组的大时间戳
    private long getMaxTicks(String groupId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String query = "SELECT Max(msg_ticks) FROM messages WHERE group_id = ?";
        Cursor cursor = db.rawQuery(query, new String[]{groupId});
        long minTicks = 0;
        if (cursor.moveToFirst()) {
            minTicks = cursor.getLong(0);
        }
        cursor.close();
        db.close();
        return minTicks;
    }

    // 删除某条消息
    public void deleteMessage(String msgId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("messages", "msg_id = ?", new String[]{msgId});
        db.close();
    }

    // 清空某个组的消息
    public void clearGroupMessages(String groupId) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete("messages", "group_id = ?", new String[]{groupId});
        db.close();
    }
}